package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.impl.OrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;


    //每分钟执行一次，处理超时的订单
    @Scheduled(cron = "0 * * * * ? ")
    public void processTimeOutOrder(){
        log.info("处理超时的订单：{}", LocalDateTime.now());

        //处理待付款的超时订单
        List<Orders> ordersList= orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,LocalDateTime.now().minusMinutes(15));

        ordersList.forEach((orders -> {
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单支付超时");
            orders.setStatus(Orders.CANCELLED);
            orderMapper.update(orders);
        }));


    }

    //每天凌晨一点处理上一天一直在派送中的订单
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("处理一直在派送中的订单：{}",LocalDateTime.now());

        List<Orders> ordersList= orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now().minusMinutes(60));

        ordersList.forEach((orders -> {
            //orders.setCancelTime(LocalDateTime.now());
            //orders.setCancelReason("订单支付超时");
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }));
    }
}
